import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'dart:io';
import 'package:path/path.dart' as path;

import '../../../data/models/upload/upload_task.dart';
import '../../../domain/providers/upload_queue_provider.dart';

class UploadListScreen extends StatefulWidget {
  const UploadListScreen({Key? key}) : super(key: key);

  @override
  State<UploadListScreen> createState() => _UploadListScreenState();
}

class _UploadListScreenState extends State<UploadListScreen> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('自动备份'),
        actions: [
          IconButton(
            icon: const Icon(Icons.share),
            onPressed: () {
              // 分享功能
            },
          ),
        ],
      ),
      body: Consumer<UploadQueueProvider>(
        builder: (context, uploadQueueProvider, child) {
          // 获取正在上传和等待上传的任务
          final pendingAndProcessingTasks = [
            ...uploadQueueProvider.processingTasks,
            ...uploadQueueProvider.pendingTasks,
          ];

          // 获取已完成的任务
          final completedTasks = uploadQueueProvider.completedTasks;

          // 获取失败的任务
          final failedTasks = uploadQueueProvider.failedTasks;

          // 所有任务的数量
          final totalTasksCount = uploadQueueProvider.tasks.length;

          // 正在上传的任务数量
          final processingTasksCount =
              uploadQueueProvider.processingTasks.length;

          return Column(
            children: [
              // 当前状态信息
              Container(
                padding: const EdgeInsets.symmetric(
                  horizontal: 16,
                  vertical: 8,
                ),
                color: Colors.grey.shade100,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(
                      '正在备份($processingTasksCount/$totalTasksCount)',
                      style: const TextStyle(color: Colors.blue),
                    ),
                    TextButton(
                      onPressed:
                          totalTasksCount > 0
                              ? () => _showPauseAllDialog(
                                context,
                                uploadQueueProvider,
                              )
                              : null,
                      child: const Text('全部暂停'),
                    ),
                  ],
                ),
              ),

              // 任务列表
              Expanded(
                child: ListView(
                  children: [
                    // 显示前10个正在上传/等待上传的任务
                    ...pendingAndProcessingTasks
                        .take(10)
                        .map(
                          (task) => _buildTaskItem(
                            context,
                            task,
                            uploadQueueProvider,
                          ),
                        ),

                    // 如果有已完成的任务，显示标题
                    if (completedTasks.isNotEmpty)
                      Padding(
                        padding: const EdgeInsets.all(16.0),
                        child: Text(
                          '已完成 (${completedTasks.length})',
                          style: Theme.of(context).textTheme.titleMedium,
                        ),
                      ),

                    // 显示已完成的任务
                    ...completedTasks.map(
                      (task) =>
                          _buildTaskItem(context, task, uploadQueueProvider),
                    ),

                    // 如果有失败的任务，显示标题
                    if (failedTasks.isNotEmpty)
                      Padding(
                        padding: const EdgeInsets.all(16.0),
                        child: Text(
                          '失败 (${failedTasks.length})',
                          style: Theme.of(
                            context,
                          ).textTheme.titleMedium?.copyWith(color: Colors.red),
                        ),
                      ),

                    // 显示失败的任务
                    ...failedTasks.map(
                      (task) =>
                          _buildTaskItem(context, task, uploadQueueProvider),
                    ),
                  ],
                ),
              ),
            ],
          );
        },
      ),
    );
  }

  Widget _buildTaskItem(
    BuildContext context,
    UploadTask task,
    UploadQueueProvider provider,
  ) {
    // 获取文件名
    final fileName = path.basename(task.fileName);

    // 获取文件大小显示
    final fileSizeStr = _formatFileSize(task.fileSize);

    // 获取已上传大小显示
    final uploadedSizeStr =
        task.status == UploadTaskStatus.completed
            ? fileSizeStr
            : '${_formatFileSize((task.fileSize * task.progress).toInt())}/$fileSizeStr';

    // 获取上传速度显示
    final speedStr =
        task.status == UploadTaskStatus.uploading
            ? '${_formatSpeed(task.fileSize * 0.1)}' // 模拟速度
            : '0B/s';

    // 获取任务状态显示
    String statusStr;
    Widget statusWidget;

    switch (task.status) {
      case UploadTaskStatus.uploading:
        statusStr = '${(task.progress * 100).toInt()}%';
        statusWidget = Text(
          statusStr,
          style: const TextStyle(color: Colors.blue),
        );
        break;
      case UploadTaskStatus.pending:
        statusStr = '等待中';
        statusWidget = Text(
          statusStr,
          style: const TextStyle(color: Colors.grey),
        );
        break;
      case UploadTaskStatus.completed:
        statusStr = '已完成';
        statusWidget = Text(
          statusStr,
          style: const TextStyle(color: Colors.green),
        );
        break;
      case UploadTaskStatus.failed:
        statusStr = '失败';
        statusWidget = Text(
          statusStr,
          style: const TextStyle(color: Colors.red),
        );
        break;
      case UploadTaskStatus.paused:
        statusStr = '已暂停';
        statusWidget = Text(
          statusStr,
          style: const TextStyle(color: Colors.orange),
        );
        break;
      default:
        statusStr = '未知';
        statusWidget = Text(statusStr);
    }

    // 获取文件缩略图
    Widget thumbnailWidget;
    try {
      if (File(task.filePath).existsSync()) {
        thumbnailWidget = Image.file(
          File(task.filePath),
          width: 60,
          height: 60,
          fit: BoxFit.cover,
          errorBuilder: (_, __, ___) => _defaultThumbnail(),
        );
      } else {
        thumbnailWidget = _defaultThumbnail();
      }
    } catch (e) {
      thumbnailWidget = _defaultThumbnail();
    }

    return ListTile(
      leading: ClipRRect(
        borderRadius: BorderRadius.circular(4),
        child: thumbnailWidget,
      ),
      title: Text(fileName, overflow: TextOverflow.ellipsis, maxLines: 1),
      subtitle: Text(uploadedSizeStr),
      trailing: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          // 只在上传中状态显示速度信息，其他状态保留空间但不显示内容
          task.status == UploadTaskStatus.uploading
              ? Text(speedStr)
              : const SizedBox(width: 50), // 保持布局一致的空间
          const SizedBox(width: 16),
          statusWidget,
        ],
      ),
      onLongPress: () => _showTaskOptionsDialog(context, task, provider),
    );
  }

  Widget _defaultThumbnail() {
    return Container(
      width: 60,
      height: 60,
      color: Colors.grey.shade300,
      child: Icon(Icons.insert_drive_file, color: Colors.grey.shade700),
    );
  }

  String _formatFileSize(int bytes) {
    if (bytes < 1024) {
      return '${bytes}B';
    } else if (bytes < 1024 * 1024) {
      return '${(bytes / 1024).toStringAsFixed(1)}KB';
    } else if (bytes < 1024 * 1024 * 1024) {
      return '${(bytes / (1024 * 1024)).toStringAsFixed(1)}MB';
    } else {
      return '${(bytes / (1024 * 1024 * 1024)).toStringAsFixed(1)}GB';
    }
  }

  String _formatSpeed(double bytesPerSecond) {
    if (bytesPerSecond < 1024) {
      return '${bytesPerSecond.toStringAsFixed(1)}B/s';
    } else if (bytesPerSecond < 1024 * 1024) {
      return '${(bytesPerSecond / 1024).toStringAsFixed(1)}KB/s';
    } else {
      return '${(bytesPerSecond / (1024 * 1024)).toStringAsFixed(1)}MB/s';
    }
  }

  void _showTaskOptionsDialog(
    BuildContext context,
    UploadTask task,
    UploadQueueProvider provider,
  ) {
    showModalBottomSheet(
      context: context,
      builder:
          (context) => Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              ListTile(
                leading: const Icon(Icons.info_outline),
                title: const Text('文件信息'),
                onTap: () {
                  Navigator.pop(context);
                  _showTaskInfoDialog(context, task);
                },
              ),
              if (task.status == UploadTaskStatus.uploading)
                ListTile(
                  leading: const Icon(Icons.pause),
                  title: const Text('暂停'),
                  onTap: () {
                    provider.pauseTask(task.id);
                    Navigator.pop(context);
                  },
                ),
              if (task.status == UploadTaskStatus.paused)
                ListTile(
                  leading: const Icon(Icons.play_arrow),
                  title: const Text('继续'),
                  onTap: () {
                    provider.resumeTask(task.id);
                    Navigator.pop(context);
                  },
                ),
              if (task.status == UploadTaskStatus.failed)
                ListTile(
                  leading: const Icon(Icons.refresh),
                  title: const Text('重试'),
                  onTap: () {
                    provider.retryTask(task.id);
                    Navigator.pop(context);
                  },
                ),
              ListTile(
                leading: const Icon(Icons.cancel),
                title: const Text('取消'),
                onTap: () {
                  provider.cancelTask(task.id);
                  Navigator.pop(context);
                },
              ),
            ],
          ),
    );
  }

  void _showTaskInfoDialog(BuildContext context, UploadTask task) {
    final fileName = path.basename(task.fileName);
    final fileSizeStr = _formatFileSize(task.fileSize);
    final progress = task.progress * 100;

    showDialog(
      context: context,
      builder:
          (context) => AlertDialog(
            title: const Text('文件信息'),
            content: Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text('文件名: $fileName'),
                const SizedBox(height: 8),
                Text('文件大小: $fileSizeStr'),
                const SizedBox(height: 8),
                Text('上传进度: ${progress.toStringAsFixed(1)}%'),
                const SizedBox(height: 8),
                Text('状态: ${_getStatusString(task.status)}'),
                const SizedBox(height: 8),
                Text('创建时间: ${task.createTime.toString().substring(0, 19)}'),
                if (task.errorMessage != null) ...[
                  const SizedBox(height: 8),
                  Text(
                    '错误信息: ${task.errorMessage}',
                    style: const TextStyle(color: Colors.red),
                  ),
                ],
              ],
            ),
            actions: [
              TextButton(
                onPressed: () => Navigator.pop(context),
                child: const Text('关闭'),
              ),
            ],
          ),
    );
  }

  String _getStatusString(UploadTaskStatus status) {
    switch (status) {
      case UploadTaskStatus.uploading:
        return '上传中';
      case UploadTaskStatus.pending:
        return '等待中';
      case UploadTaskStatus.completed:
        return '已完成';
      case UploadTaskStatus.failed:
        return '失败';
      case UploadTaskStatus.paused:
        return '已暂停';
      case UploadTaskStatus.cancelled:
        return '已取消';
      default:
        return '未知';
    }
  }

  void _showPauseAllDialog(BuildContext context, UploadQueueProvider provider) {
    showDialog(
      context: context,
      builder:
          (context) => AlertDialog(
            title: const Text('暂停所有上传'),
            content: const Text('确定要暂停所有正在上传的任务吗？'),
            actions: [
              TextButton(
                onPressed: () => Navigator.pop(context),
                child: const Text('取消'),
              ),
              TextButton(
                onPressed: () {
                  // 暂停所有上传中的任务
                  for (final task in provider.processingTasks) {
                    provider.pauseTask(task.id);
                  }
                  Navigator.pop(context);
                },
                child: const Text('确定'),
              ),
            ],
          ),
    );
  }
}
